#include "adc.h"


void adc_init(){

	GPIO_InitTypeDef GPIO_InitStructure;
	ADC_InitTypeDef ADC_InitStructure;
	
	//GPIO初始化
	RCC_APB2PeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);  //打开ADC1的时钟
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;//输出模式
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;//
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	//ADC初始化
//	RCC_ADCCLKConfig(RCC_PCLK2_Div4);//设置ADC时钟
	ADC_DeInit(ADC1); //复位 ADC1,将外设 ADC1 的全部寄存器重设为缺省值
	/* Initialize ADC structure */
	ADC_StructInit(&ADC_InitStructure); //初始化成员，下面再给成员赋值
	ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;//f030是12bit
	ADC_InitStructure.ADC_ContinuousConvMode = ENABLE; 
	ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
	ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;//右对齐
	ADC_InitStructure.ADC_ScanDirection = ADC_ScanDirection_Upward;
	ADC_Init(ADC1, &ADC_InitStructure); //根据指定的参数初始化外设 ADCx
	
	ADC_ChannelConfig(ADC1, ADC_Channel_5 , ADC_SampleTime_239_5Cycles);
	
	/* ADC Calibration */
	ADC_GetCalibrationFactor(ADC1);

	/* Enable the ADC peripheral */
	ADC_Cmd(ADC1, ENABLE);     

	/* Wait the ADRDY flag */
	while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_ADRDY)); 
	/* ADC1 regular Software Start Conv */ 
	ADC_StartOfConversion(ADC1);
}

void adc_stop(){
	// RCC_APB2PeriphClockCmd(RCC_AHBPeriph_GPIOA, DISABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, DISABLE);
}
uint16_t get_adc_val(uint8_t ch){
	//设置指定 ADC 的规则组通道，设置它们的转化顺序和采样时间
	ADC_ChannelConfig(ADC1, ch, ADC_SampleTime_239_5Cycles);//ADC1,规则采样顺序值为 1,采样时间为 239.5 周期
	ADC_ContinuousModeCmd(ADC1, ENABLE); //使能软件转换功能
	while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC )== RESET);//等待转换结束
	return ADC_GetConversionValue(ADC1); //返回最近一次 ADC1 规则组的转换结果

}

uint32_t ADC_Check(void){
	uint32_t ResulVolt = 0;
	uint8_t i;
	for (i = 0; i < 8; i++)
	{
		while(ADC_GetFlagStatus(ADC1,ADC_FLAG_EOC)==RESET);
		ResulVolt +=(uint32_t) ADC_GetConversionValue(ADC1);
	}
	ResulVolt = ResulVolt >> 3;

	//printf(">>>ResulVolt: %d \n\r",ResulVolt);

	ResulVolt = (ResulVolt*3300)>>12;

	ResulVolt = ResulVolt*6;
	
	return ResulVolt;
}


